﻿using Microsoft.AspNetCore.SignalR;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Qy.Web.Hubs;

public class MessageHub : Hub
{
    //创建用户集合，用于存储所有链接的用户数据
    public static readonly List<OnlineUsers> clientUsers = new();
    private readonly NoticeKeyService _noticeKeyService;
    private readonly ILoginUserInfoMethods _LoginUserInfoMethods;

    public MessageHub(NoticeKeyService noticeService, ILoginUserInfoMethods LoginUserInfoMethods)
    {
        _noticeKeyService = noticeService;
        _LoginUserInfoMethods = LoginUserInfoMethods;
    }

    // 客户端调用服务端的方法
    //public async Task SendMessage(string user, string message)
    //{
    //    // 服务端主动调用客户端的方法
    //    await Clients.All.SendAsync("ReceiveMessage", data);

    //    // 常用方法
    //    // 给所有人发送消息
    //    await Clients.All.SendAsync("ReceiveMessage", data);
    //    // 给组里所有人发消息
    //    await Clients.Group("Users").SendAsync("ReceiveMsg", data);
    //    // 给调用方法的那个人发消息
    //    await Clients.Caller.SendAsync("ReceiveMessage", data);
    //    // 给除了调用方法的以外所有人发消息
    //    await Clients.Others.SendAsync("ReceiveMessage", data);
    //    // 给指定connectionId的人发消息
    //    await Clients.User(connectionId).SendAsync("ReceiveMessage", data);
    //    // 给指定connectionId的人发消息
    //    await Clients.Client(connectionId).SendAsync("ReceiveMessage", data);
    //    // 给指定connectionId的人发消息，同时指定多个connectionId
    //    await Clients.Clients(IReadOnlyList <> connectionIds).SendAsync("ReceiveMessage", data);
    //}


    // Console.WriteLine($"{DateTime.Now}：{name},{Context.ConnectionId}连接服务端success，----当前已连接{clientUsers.Count}个");
    // Clients.All.SendAsync("welcome", $"欢迎您：{name},-----当前时间：{DateTime.Now}");

    //   await Clients.All.SendAsync(HubsConstant.OnlineNum, clientUsers.Count);
    //  await Clients.All.SendAsync(HubsConstant.OnlineUser, clientUsers);


    //给当前的连接分组 可以进行同一组接收消息 也可以用Token获取机构权限
    //await Groups.AddToGroupAsync(Context.ConnectionId, "测试组");

    //给当前连接返回消息 .Clients可以发多个连接ID
    //  await Clients.Client(connId).SendAsync(HubsConstant.OnlineUser, clientUsers);


    //  Console.WriteLine($"{DateTime.Now}：{name},{connId}连接服务端success，当前已连接{clientUsers.Count}个");
    //await Clients.All.SendAsync("welcome", $"欢迎您：{name},当前时间：{DateTime.Now}");
    //var sendMs = await SendNotice();
    //await Clients.All.SendAsync("welcome", new{title = sendMs.Title,data = sendMs.Content });




    private async Task<ViewNotice> SendNotice()
    {
        var result = await _noticeKeyService.ReadOneAsync(1);
        return result;
    }

    /// <summary>
    /// 客户端连接
    /// </summary>
    /// <returns></returns>
    public override async Task<Task> OnConnectedAsync()
    {
        string connId = Context.ConnectionId;

        var name = Context.User.Identity.Name;
        var ip = HttpContextExtension.GetClientUserIp(App.HttpContext);
        var user = clientUsers.Any(u => u.ConnnectionId == connId);
        int loginUserId = _LoginUserInfoMethods.LoginUserId();
        if (!user && Context.User.Identity.IsAuthenticated)
        {
            OnlineUsers users = new(connId, name, loginUserId, ip){};
            clientUsers.Add(users);
            await Clients.All.SendAsync("welcome", $"欢迎您：{name},当前时间：{DateTime.Now}");
        }
        return base.OnConnectedAsync();

    }

    /// <summary>
    /// 连接终止
    /// </summary>
    /// <returns></returns>
    public override Task OnDisconnectedAsync(Exception exception)
    {
        var user = clientUsers.Where(p => p.ConnnectionId == Context.ConnectionId).FirstOrDefault();
        if (user != null)
        {
            clientUsers.Remove(user);
        }
        return Task.FromResult(base.OnDisconnectedAsync(exception));
    }


    /// <summary>
    /// 发送信息
    /// </summary>
    /// <param name="connectId"></param>
    /// <param name="userName"></param>
    /// <param name="message"></param>
    /// <returns></returns>
    [HubMethodName("SendMessage")]
    public async Task SendMessage(string connectId, string userName, string message)
    {
       // Console.WriteLine($"{connectId},message={message}");
        await Clients.Client(connectId).SendAsync("receiveChat", new { userName, message });
    }

    // /// <summary>
    // /// 强制下线
    //  /// </summary>
    //  /// <param name="input"></param>
    //  /// <returns></returns>
    //public async Task ForceOffline(OnlineUsers input)
    //{
    //    await _onlineUserHubContext.Clients.Client(input.ConnnectionId).ForceOffline("强制下线");
    //}
}

